import okx.MarketData as MarketData
import pandas as pd
import time
import json

cryptolist = [
    #"BTC-USDT",
    "ETH-USDT",
    #"SOL-USDT",
    #"ADA-USDT",
    #"DOGE-USDT",
    #"XRP-USDT",
    ]

def get_PricefromJson(result):
    price = 0
    try:
        price = result["data"][0]['last']
    except:
        pass
    return price

def cal_macd(raw_data):
    # 整理为DataFrame
    df = pd.DataFrame(raw_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote', 'confirm'])
    df["close"] = df["close"].astype(float)
    df['Date'] = pd.to_datetime(df['timestamp'].astype(int), unit='ms')
    df.set_index('Date', inplace=True)
    df = df.sort_index()
    # MACD计算
    df['ema12'] = df['close'].ewm(span=12, adjust=False).mean()
    df['ema26'] = df['close'].ewm(span=26, adjust=False).mean()
    df['dif'] = df['ema12'] - df['ema26']
    df['dea'] = df['dif'].ewm(span=9, adjust=False).mean()
    df['macd'] = 2 * (df['dif'] - df['dea'])  # MACD柱子
    return df

def cal_kdj(raw_data):
    # 创建DataFrame
    df = pd.DataFrame(raw_data, columns=[
        'timestamp', 'open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote', 'confirm'
    ])
    df['Date'] = pd.to_datetime(df['timestamp'].astype(int), unit='ms')
    df.set_index('Date', inplace=True)
    # 转换数值型
    for col in ['open', 'high', 'low', 'close', 'vol']:
        df[col] = df[col].astype(float)
    df = df.sort_index()  # 按时间升序

    # -----------------
    # KDJ计算部分
    # -----------------
    n = 9  # 常用周期，样本太短建议设成比样本长度小的值(如3)
    low_list = df['low'].rolling(window=n, min_periods=1).min()
    high_list = df['high'].rolling(window=n, min_periods=1).max()
    rsv = (df['close'] - low_list) / (high_list - low_list) * 100

    df['K'] = rsv.ewm(com=2, adjust=False).mean()  # K线
    df['D'] = df['K'].ewm(com=2, adjust=False).mean()  # D线
    df['J'] = 3 * df['K'] - 2 * df['D']  # J线
    return df

def is_macd_bar_increasing(df, consecutive=2):
    """
    判断MACD Bar最近是否有consecutive根连续放大
    放大指绝对值连续增加
    """
    macd_bars = df['macd'].values[-consecutive:]
    if len(macd_bars) < consecutive:
        return False
    # 取出需要比较的若干根（如最后两根比较一次，最后三根比较两次）
    for i in range(1, len(macd_bars)):
        if abs(macd_bars[i]) <= abs(macd_bars[i-1]):
            return False
    return True

def check_recent_trend(values):
    # 输入检查
    if len(values) < 3:
        return "列表长度不足3"
    # 最近三小时的数值(包括最新一个)
    recent = values[-3:]
    last = values[-1]
    if last > 0:
        # 检查递增
        if recent[0] < recent[1] < recent[2]:
            return '<p style="color: green;"> +++最近三个周期数值递增，MACD绿柱增强中+++ </p>'
        elif recent[0] > recent[1] > recent[2]:
            return '<p style="color: green;"> ---最近三个周期数值递增，MACD绿柱减弱中--- </p>'
        else:
            return 'MACD零轴上方无序震荡中'
    else:
        # 检查递减
        if recent[0] > recent[1] > recent[2]:
            return '<p style="color: red;"> +++最近三个周期数值递减，MACD红柱增强中+++ </p>'
        elif recent[0] < recent[1] < recent[2]:
            return '<p style="color: red;"> ---最近三个周期数值递增，MACD红柱减弱中--- </p>'
        else:
            return 'MACD零轴下方无序震荡中'

def get_rawdata(instId,bar='1H'):
    flag = "0"
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    result = marketDataAPI.get_candlesticks(instId, bar=str(bar))
    raw_data = result["data"]
    return raw_data

def macdcheck(instId, bar = '1H'):
    result = ""
    raw_data = get_rawdata(instId, bar)
    df = cal_macd(raw_data)
    macd_bars = df['macd'].values[-10:]
    #print (df)
    result = "<br/>" + instId + " macd=" + str(macd_bars)
    result += "<br/>" + check_recent_trend(macd_bars)
    df2 = cal_kdj(raw_data)
    result += "<br/> K= " + str(df2["K"].values[-1:][0])
    result += "<br/> D= " + str(df2["D"].values[-1:][0])
    result += "<br/> J= " + str(df2["J"].values[-1:][0])
    result += "<br/><br/>"
    #if is_macd_bar_increasing(df):
    #    result = "<br/>" + instId + " has 2 bar increasing\n"
    return result

def check_crypto_tec(clist, bar = '1H'):
    result = ""
    for c in clist:
        #print ("bar = ", bar)
        result += macdcheck(c, bar)
    if len(result) == 0:
        result = "nothing worth to watch!!"
    return result

def write_crypto():
    fd = open("crypto.txt","w")
    result = "========================Main========================\n"
    try:
        flag = "0"  # 实盘:0 , 模拟盘：1
        marketDataAPI =  MarketData.MarketAPI(flag=flag)
        resultBTC = marketDataAPI.get_ticker(instId="BTC-USDT")
        print (resultBTC)
        result += "BTC = " + str(get_PricefromJson(resultBTC)) +"\n"

        resultETH = marketDataAPI.get_ticker(instId="ETH-USDT")
        print (resultETH)
        result += "ETH = " + str(get_PricefromJson(resultETH)) +"\n"

        resultSOL = marketDataAPI.get_ticker(instId="SOL-USDT")
        print (resultSOL)
        result += "SOL = " + str(get_PricefromJson(resultSOL)) +"\n"

        resultADA = marketDataAPI.get_ticker(instId="ADA-USDT")
        print (resultADA)
        result += "ADA = " + str(get_PricefromJson(resultADA)) +"\n"

        resultDOGE = marketDataAPI.get_ticker(instId="DOGE-USDT")
        print (resultDOGE)
        result += "DOGE = " + str(get_PricefromJson(resultDOGE)) +"\n"

        resultXRP = marketDataAPI.get_ticker(instId="XRP-USDT")
        print (resultXRP)
        result += "XRP = " + str(get_PricefromJson(resultXRP)) +"\n"
    except:
        pass 
    fd.write(result)
    fd.close()

if __name__ == '__main__':
    result = check_crypto_tec(cryptolist, "1H")
    print (result)
